package com.base.cn.platform.os.interceptor;

import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * App拦截器
 * @author s.li
 * @date 2018/11/19
 */
@Slf4j
public class AppInterceptor implements HandlerInterceptor {
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    @Autowired
    private SignCheck signCheck;
    @Autowired
    private Environment environment;
    @Autowired
    private CustomCacheChannel customCacheChannel;
    //请求来源参数名
    private static String REQUEST_FORM_NAME = "requestForm";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        log.info("=============================sign check url:"+requestURI);
        if(!RequestMethod.POST.toString().equals(method)){
            response.getWriter().print(gson.toJson(ResultUtil.ERROR("必须是POST请求")));
            return false;
        }
        //获取系统缓存的密钥
        String privateKey = environment.getProperty("private.key");
        //验证密钥
        boolean s = signCheck.checkPrivateKey(request,privateKey);
        if(!s){
            response.getWriter().print(gson.toJson(ResultUtil.ERROR("接口密钥错误")));
            return false;
        }
        //验证签名
        s = signCheck.signCheck(request);
        if(!s){
            response.getWriter().print(gson.toJson(ResultUtil.ERROR("接口签名错误")));
            return false;
        }
        String userId = request.getParameter("userId");
        if(StringUtils.isNotEmpty(userId)&&!userId.equals("0")){
            log.info("========================userId:"+userId);
            String token = (String)customCacheChannel.get(J2CacheRegion.THIRTY_DAY_REGION.getKey(),userId).getValue();
            String _token = request.getParameter("token");
            log.info("========================_token:"+_token);
            if(_token==null || token==null || !token.equals(_token)){
                HashMap<Object, Object> resultMap = new HashMap<>();
                resultMap.put("success",false);
                resultMap.put("loginStatus",false) ;
                if(_token==null || token==null){
                    resultMap.put("message","请登录后再操作");
                    response.getWriter().print(gson.toJson(resultMap));
                    return false;
                } if(!token.equals(_token)){
                    resultMap.put("message","账号已在其它平台登录");
                    response.getWriter().print(gson.toJson(resultMap));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
